<?php
namespace app\admin\model;
use think\Model;
use think\Db;
use think\Cookie;
//1.检测em_admin表中用户是否存在或者是否被禁用
//2.检测密码是否正确
//3.将数据写入session

class Admin extends Model{
	protected $pk = 'id';
	public function check_login($username,$password){
		// dump($usename);die;
		$info = Db::name('admin')->where("username",$username)->find();
		if(!$info){
			return json(['code'=>0,'msg'=>'该用户不存在']);
		}
		$rule = Db::name('admin_role')->field('role_id')->where("admin_id",$info['id'])->find();
		if($info['status'] == 0 && $rule['role_id'] != 1 && $info['on_off'] == 0){
			return json(['code'=>0, 'msg'=>'该用户被禁用']);
		}
		if($password !=$info['password']){
			return json(['code'=>0,'msg'=>'密码错误']);
		}
		Cookie::set('admin',$info,18000);
		//保存管理员名
		Cookie::set('username',$info['username'],18000);
		//保存管理员ID
		Cookie::set('id',$info['id'],18000);
		//保存最后登陆时间
		$time = date('Y-m-d H:i:s');
		$this->where('id',$info['id'])->setField('login_time',$time);
		//保存最后登陆IP
		$ip = request()->ip();
		$this->where('id',$info['id'])->setField('login_ip',$ip);
		return json(array('code'=>1,'msg'=>'登陆成功'));
	}

	//关联admin和admin_role的admin_id 控制器中的admin.php 获取这里的值
	public function getAllData($status){
		$start = input('get.start');
		$end = input('get.end');
		//只显示状态为传过来的值的数据
		$where ="status = $status";

		//开始时间
		if ($start) {
			$start = strtotime($start);
			$where .= " and UNIX_TIMESTAMP(a.add_time) >= $start";
		}
		//结束时间
		if ($end) {
			$end = strtotime($end)+60*60*24;
			$where .= " and UNIX_TIMESTAMP(a.add_time) <= $end";
		}

		// echo $where;
		//当前$this指Admin模型
		$data = $this->alias('a')->join('em_admin_role b','a.id = b.admin_id')->field('a.*,b.role_id')->where($where)->order('id desc')->paginate(10);
		// dump($data);
		return $data;
		
	}
	//添加管理员
	public function addAdmin($data){

		$info = $this->where("username",$data['username'])->find();

		if($info){
			return false;
		}

		unset($data['role_id']);
		return $this->insertGetId($data);
	}
	//修改管理员
	public function editAdmin($id){
		
		$data = Db::name('admin')->alias('a')->join('em_admin_role b','a.id = b.admin_id')->field('a.*,b.role_id,b.admin_id')->where('a.id',$id)->find();
		// dump($data);die;
		
		
		return $data;
	}
	


}
	


